from PyQt5.QtWidgets import QWidget,QHeaderView,QTableWidgetItem,QLineEdit,QPushButton,QMessageBox,QLabel
from PyQt5.QtCore import Qt,pyqtSignal
from PyQt5.QtGui import QDoubleValidator
from ui.uiConfigThresh import Ui_ConfigThresh
from util import warnTip,errorTip,okTip
from db import db

class ConfigThreshWidget(QWidget,Ui_ConfigThresh):
    tipSignal=pyqtSignal(str)
    def __init__(self,parent=None):
        super(ConfigThreshWidget,self).__init__(parent)
        self.con=db.connect(sscursor=True)
        self.deviceList=db.getDeviceList(self.con)
        self.setupUi(self)
        self.setupOnce = False
        self.connectSignals()
        self.initUi()

    def initUi(self):
        for device in self.deviceList:
            self.cb_device.addItem(device['device_name'])
        self.setup(self.deviceList[0]['table_name'])
        self.currentIndex=0

    def setup(self,tableName):
        self.setupOnce=True
        config=db.getConfigThresh(self.con,tableName)
        config=eval(config)
        config=config["thresh"]
        self.table.clear()
        labels = ['字段名', '故障下限', '故障上限', '预警下限', '预警上限', '单位', '']
        self.table.setColumnCount(len(labels))
        self.table.setHorizontalHeaderLabels(labels)
        self.table.horizontalHeader().setVisible(True)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.setStyleSheet("QLineEdit{border-width:0;border-style:outset}")
        self.table.setRowCount(len(config)+1)
        for row,key in enumerate(config.keys()):
            item=QTableWidgetItem(key)
            item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row,0,item)
            le=QLineEdit(str(config[key]["error"][0]))
            le.setAlignment(Qt.AlignCenter)
            le.setValidator(QDoubleValidator(le))
            self.table.setCellWidget(row, 1, le)
            le = QLineEdit(str(config[key]["error"][1]))
            le.setAlignment(Qt.AlignCenter)
            le.setValidator(QDoubleValidator(le))
            self.table.setCellWidget(row, 2, le)
            le = QLineEdit(str(config[key]["warn"][0]))
            le.setAlignment(Qt.AlignCenter)
            le.setValidator(QDoubleValidator(le))
            self.table.setCellWidget(row, 3, le)
            le = QLineEdit(str(config[key]["warn"][1]))
            le.setAlignment(Qt.AlignCenter)
            le.setValidator(QDoubleValidator(le))
            self.table.setCellWidget(row, 4, le)
            label = QLabel(str(config[key]["unit"]))
            label.setAlignment(Qt.AlignCenter)
            self.table.setCellWidget(row, 5, label)
            pb=QPushButton("删除")
            pb.setProperty("row",row)
            pb.clicked.connect(self.removeItem)
            self.table.setCellWidget(row,6,pb)
        pbAddRow=QPushButton("添加")
        pbAddRow.clicked.connect(self.addRow)
        self.table.setCellWidget(self.table.rowCount()-1,0,pbAddRow)

    def connectSignals(self):
        self.pbSave.clicked.connect(self.saveClicked)
        self.cb_device.currentIndexChanged.connect(self.deviceChange)

    def saveClicked(self):
        config=self.parseConfig()
        tableName=self.deviceList[self.cb_device.currentIndex()]['table_name']
        self.save(config,tableName)

    def deviceChange(self,idx):
        if self.setupOnce:
            config = self.parseConfig()
            tableName = self.deviceList[self.currentIndex]['table_name']
            self.save(config, tableName)
        self.setup(self.deviceList[idx]['table_name'])
        self.currentIndex = idx;

    def removeItem(self):
        row=self.sender().property("row")
        self.table.removeRow(row)

    def addRow(self):
        row=self.table.rowCount()-1
        self.table.removeCellWidget(row,0)

        item = QTableWidgetItem()
        item.setTextAlignment(Qt.AlignCenter)
        self.table.setItem(row,0,item)
        for col in range(1,5):
            le = QLineEdit()
            le.setAlignment(Qt.AlignCenter)
            le.setValidator(QDoubleValidator(le))
            self.table.setCellWidget(row, col, le)

        pb = QPushButton("删除")
        pb.setProperty("row", row)
        pb.clicked.connect(self.removeItem)
        self.table.setCellWidget(row, 5, pb)
        self.table.insertRow(row+1)
        pbAddRow=QPushButton("添加")
        pbAddRow.clicked.connect(self.addRow)
        self.table.setCellWidget(row+1, 0, pbAddRow)

    def parseConfig(self):
        config = {}
        for row in range(self.table.rowCount() - 1):
            key = self.table.item(row, 0).text()
            if key == '':
                self.tipSignal.emit(warnTip("字段名为空，条目不会被保存"))
                continue
            error = [0, 0]
            warn = [0, 0]
            try:
                error[0] = eval(self.table.cellWidget(row, 1).text())
                error[1] = eval(self.table.cellWidget(row, 2).text())
                warn[0] = eval(self.table.cellWidget(row, 3).text())
                warn[1] = eval(self.table.cellWidget(row, 4).text())
                unit = self.table.cellWidget(row, 5).text()
            except:
                self.tipSignal.emit(errorTip("字段{}有参数为空，条目不会被保存".format(key)))
                continue
            config[key] = {}
            config[key]['error'] = error
            config[key]['warn'] = warn
            config[key]['unit'] = unit
        config = {'thresh': config}
        return config

    def save(self,config,tableName):
        # try:
        text=str(config)
        db.saveConfigThresh(self.con,tableName,text)
        self.tipSignal.emit(okTip("阈值配置保存成功"))
        # except:
        #     QMessageBox.critical(self, "错误", "写入文件失败", QMessageBox.Cancel,QMessageBox.Cancel)



if __name__=="__main__":
    import sys
    from PyQt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    exe = ConfigThreshWidget()
    exe.show()
    sys.exit(app.exec_())